<?php
// 【最终完整版】m-merchant/profile_data.php
header('Content-Type: application/json; charset=utf-8');

function verify_token($token) {
    $secret_key = 'kkcc.vip-is-the-best-!@#$%';
    if (!$token) return null; $token_parts = explode('.', $token);
    if (count($token_parts) !== 3) return null; list($h, $p, $s) = $token_parts;
    $sig = base64_decode(str_replace(['-','_'],['+','/'], $s));
    $exp_sig = hash_hmac('sha256', $h.".".$p, $secret_key, true);
    if (!hash_equals($exp_sig, $sig)) return null;
    $payload = json_decode(base64_decode(str_replace(['-','_'],['+','/'], $p)), true);
    if ($payload === null || ($payload['exp']??0) < time()) return null;
    return $payload['data'];
}
function get_authorization_header() {
    if (isset($_SERVER['Authorization'])) return trim($_SERVER["Authorization"]);
    if (isset($_SERVER['HTTP_AUTHORIZATION'])) return trim($_SERVER["HTTP_AUTHORIZATION"]);
    if (function_exists('getallheaders')) {
        $h = getallheaders(); if (isset($h['Authorization'])) return trim($h['Authorization']);
    } return null;
}

$user_data = verify_token(str_replace('Bearer ', '', get_authorization_header()));
if ($user_data === null) {
    http_response_code(401);
    echo json_encode(['status' => -99, 'msg' => '登录失效']);
    exit();
}

include_once("../untils/conn.php");
mysqli_query($con, "set names utf8");

$proxy_id = (int)$user_data['proxy_id'];
$proxy_acc = mysqli_real_escape_string($con, $user_data['proxy_acc']);
$response = ['status' => -1, 'msg' => '无法获取代理信息'];
$data_to_send = [];

$sql_proxy = "SELECT * FROM proxy WHERE proxy_id = '{$proxy_id}' LIMIT 1";
$res_proxy = mysqli_query($con, $sql_proxy);

if ($res_proxy && mysqli_num_rows($res_proxy) > 0) {
    $row_proxy = mysqli_fetch_assoc($res_proxy);
    
    $data_to_send['id'] = $row_proxy['proxy_id'];
    $data_to_send['shop_name'] = $row_proxy['proxy_name'] ?: ('代理-' . $row_proxy['proxy_acc']);
    $data_to_send['avatar'] = $row_proxy['proxy_avatar'] ?: 'https://i.328888.xyz/2023/03/30/iJ8syy.png';
    $data_to_send['is_renamed'] = (bool)$row_proxy['proxy_rename_sta'];
    $data_to_send['available_balance'] = number_format($row_proxy['proxy_balance'] ?: 0, 2);
    $data_to_send['commission_type'] = (int)$row_proxy['commission_type'];
    $data_to_send['commission_value'] = (float)$row_proxy['commission_value'];

    $sql_withdrawn = "SELECT SUM(price) as total FROM revenue WHERE tixian_sta = 1 AND account = '{$proxy_acc}'";
    $res_withdrawn = mysqli_query($con, $sql_withdrawn);
    $data_to_send['withdrawn_balance'] = $res_withdrawn ? number_format(mysqli_fetch_assoc($res_withdrawn)['total'] ?: 0, 2) : '0.00';
    
    $sub_proxies_query = "SELECT proxy_id FROM proxy WHERE proxy_upid = '{$proxy_id}'";
    $sub_proxies_result = mysqli_query($con, $sub_proxies_query);
    $proxy_ids_to_query = [$proxy_id];
    if ($sub_proxies_result) { while ($sub_row = mysqli_fetch_assoc($sub_proxies_result)) { $proxy_ids_to_query[] = (int)$sub_row['proxy_id']; } }
    $proxy_ids_str = implode(',', $proxy_ids_to_query);

    $sql_count = "SELECT COUNT(*) AS count FROM oder WHERE proxy_id IN ({$proxy_ids_str})";
    $res_count = mysqli_query($con, $sql_count);
    $data_to_send['total_orders'] = $res_count ? (int)mysqli_fetch_assoc($res_count)['count'] : 0;
    
    $sql_sub_count = "SELECT COUNT(*) AS count FROM proxy WHERE proxy_upid = '{$proxy_id}'";
    $res_sub_count = mysqli_query($con, $sql_sub_count);
    $data_to_send['sub_agents_count'] = $res_sub_count ? (int)mysqli_fetch_assoc($res_sub_count)['count'] : 0;
    
    $sql_activation = "SELECT COUNT(*) AS total, SUM(CASE WHEN card_sta = 1 THEN 1 ELSE 0 END) AS active FROM oder WHERE proxy_id IN ({$proxy_ids_str})";
    $res_activation = mysqli_query($con, $sql_activation);
    if ($res_activation && $row_act = mysqli_fetch_assoc($res_activation)) {
        $total = (int)$row_act['total'];
        $active = (int)$row_act['active'];
        $data_to_send['active_rate'] = $total > 0 ? round($active / $total * 100, 1) : 0;
    } else { $data_to_send['active_rate'] = 0; }
    
    $response['status'] = 0;
    $response['data'] = $data_to_send;
}

echo json_encode($response);
mysqli_close($con);
?>